package com.example.tourism.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class UploadToOSSAndDB {
    public static void main(String[] args) {
        // 阿里云OSS配置
        String endpoint = "你的Endpoint";
        String accessKeyId = "你的AccessKeyId";
        String accessKeySecret = "你的AccessKeySecret";
        String bucketName = "你的Bucket名称";

        // 数据库配置
        String dbUrl = "数据库连接URL";
        String dbUser = "数据库用户名";
        String dbPassword = "数据库密码";

        // 上传文件到OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String objectName = "user/avatar.jpg"; // OSS上保存的文件名
        String localFile = "/path/to/your/local/image.jpg"; // 本地文件的路径

        try {
            InputStream inputStream = new FileInputStream(new File(localFile));
            ossClient.putObject(bucketName, objectName, inputStream);
            System.out.println("文件上传成功。");

            // 获取上传后的文件地址
            String fileUrl = "http://" + bucketName + "." + endpoint + "/" + objectName;

            // 更新数据库
            Connection connection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
            String sql = "UPDATE 用户表 SET 头像地址 = ? WHERE 用户ID = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, fileUrl);
            preparedStatement.setString(2, "用户ID"); // 替换为实际的用户ID
            int rowsAffected = preparedStatement.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("数据库更新成功。");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSS客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
